#include "MyModel.h"
MyModel::MyModel(QObject *parent) : QAbstractTableModel(parent)
{

}

int MyModel::rowCount(const QModelIndex &) const
{
    return 3;
}

int MyModel::columnCount(const QModelIndex &) const
{
    return 2;
}

QVariant MyModel::data(const QModelIndex &index, int role) const
{
    if(role == Qt::DisplayRole && index.column() == 0) {
        switch(index.row()) {
        case 0:
            return QString("Channel");
        case 1:
            return QString("IP");
        case 2:
            return QString("Port");
        }
    }
    else if((role == Qt::EditRole || role == Qt::DisplayRole) && index.column() == 1) {
        switch(index.row()) {
        case 0:
            return QString(QString("%1").arg(varData.channel));
        case 1:
            return QString(QString("%1.%2.%3.%4").arg(varData.ipv4[0]).arg(varData.ipv4[1]).arg(varData.ipv4[2]).arg(varData.ipv4[3]));
        case 2:
            return QString(QString("%1").arg(varData.port));
        }
    }
    return QVariant();
}

#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QDebug>
bool MyModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if(role != Qt::EditRole && index.column() != 1)
        return false;

    bool ok;
    QString pattern;
    const QString string = value.toString();
    QRegularExpression re;
    QRegularExpressionMatch match;

    switch(index.row()) {
    //Channel Modify
    case 0: {
        pattern = "[+-]?\\d+";
        re.setPattern(pattern);
        match = re.match(string);
        int temp = match.captured().toInt(&ok);

        if(ok) {
            varData.channel = temp;
        }
    }
        break;
    //IPv4 Modify
    case 1: {
        pattern = "([+-]?\\d+).([+-]?\\d+).([+-]?\\d+).([+-]?\\d+)";
        re.setPattern(pattern);
        match = re.match(string);

        for(int i = 0; i < 4; i++) {
            unsigned short temp = match.captured(i+1).toUShort(&ok);
            if(ok && temp < 256) {
                varData.ipv4[i] = (unsigned char)temp;
            }
        }
    }
        break;
    //Port Modify
    case 2: {
        pattern = "\\d+";
        re.setPattern(pattern);
        match = re.match(string);
        unsigned short temp = match.captured().toUShort(&ok);

        if(ok) {
            varData.port = temp;
        }
    }
        break;
    default:
        return false;
    }

    return true;
}

Qt::ItemFlags MyModel::flags(const QModelIndex &index) const
{
    return (index.column() == 1 ? Qt::ItemIsEditable : Qt::NoItemFlags) | QAbstractItemModel::flags(index);
}

